import Addition2 from '@/components/Addition2';
import QueryMaterial2 from '@/components/QueryMaterial2';
import {s_saveMaterialUserDefine, s_getMaterialCategoryTree, s_getMaterialDocument, s_getMaterialUserDefine, s_getOrgTargetKeysGlobal, s_getOrgTransferData, s_saveAllocateOrgGlobal, s_saveMaterialInfo, s_saveUnitData, getCommTreeByXid, s_getTableInfo, s_updateInfo, s_getSelectData, s_getMaterialDocumentCraft, s_getcommontableinfo, s_getSelectDataByCondition, status2text } from '@/services/basis';
import { getSelection } from '@/services/selections';
import { ActionType, EditableFormInstance, EditableProTable, ProCard, ProColumns, ProForm, ProFormDatePicker, ProFormInstance, ProFormRadio, ProFormSelect, ProFormText, ProTable } from '@ant-design/pro-components';
import { useModel, useRequest } from '@umijs/max';
import { Card,Image, theme,Row,Col,Tree, Space, Button, Form, Input, Modal, Radio, Select, DatePicker, Drawer, Transfer, Divider, Checkbox, Tabs, TabsProps, message} from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
 
import dayjs from 'dayjs';
import { values } from 'lodash';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';

//商品分类组 件
 function CategoryTree(props:any){
  return(
    <Tree treeData={props.tdata}  
     defaultExpandAll={true} blockNode={true}
          onClick={(e,node)=>{props.getTreeInfo(node);}}/>
  );
}


//商品档案表组件-- 注意：table_ref用于外部控制表格还原
// function MaterialTable({tdata,setMaterialCode,table_ref}){
  function MaterialTable(props:any){
  interface DataType{
    pic?:string,
    x_id:number,
    id:number, 
    cate_id:number,
    code:string,
    name:string,
    scode:string,
    cate_code:string,
    invstd:string,
    invstd2:string,
    brand:string,
    isservice:number,
    isfee:number,
    munit_code:string,
    aunit_code:string,
    rate:number,
    status:number,
    operate_time:string,
    operater_code:string,
    fnsku:string,ansi:string,
    //以下4个为视图中添加
    cate_name:string,
    operater_name:string,
    munit_name:string,
    aunit_name:string,
    //默认工艺流程和版本、日期
    craft_route_name?:string,craft_route_version?:string,craft_date?:string,isdefault?:number,
  }

   const columns:ProColumns<DataType>[]=[
    {dataIndex:'pic',title:'图片' ,editable:false,width:50,
              render:(text:any)=>{
                  var pic=text=="-"||text==undefined||text==false||text==null?'':"/basis_api/file/get?filename="+text.toString();
                  return <Image src={pic}  
                         style={{width:50,height:50}} alt='无' />
             }},
    {
      dataIndex:'cate_name',
      title:'商品分类',
    },
    {dataIndex:'id',title:'商品ID'},
    {
      dataIndex:'code',
      title:'商品编码',
    }, {
      dataIndex:'name',
      title:'名称',
    },{
      dataIndex:'scode',
      title:'简码',
    },
    {
      dataIndex:'ansi',
      title:'ANSI',
    },
    {
      dataIndex:'fnsku',
      title:'FNSKU',
    },
   {
      dataIndex:'invstd',
      title:'规格',
    },{
      dataIndex:'invstd2',
      title:'型号',
    },{
      dataIndex:'munit_name',
      title:'主计量单位',
      }, 
    {dataIndex:'craft_route_name',title:'工艺流程名'},
    {dataIndex:'isdefault',title:'是否默认',
        valueType:'select',valueEnum:{1:{text:'是'},0:{text:'否'}}
    },
    {dataIndex:'craft_date',title:'工艺日期',valueType:'date'},
    {
      dataIndex:'status',
      title:'状态',
       
      render:(text)=>text===1?<>启用</>:<Space style={{color:'red'}}>{text===2?<>停用</>:<>删除</>}</Space>,
    },
   ];

   return(
      <ProTable 
      dataSource={props.tdata} 
      columns={columns} 
      rowKey='id' 
      rowSelection={{
        type:'radio',
        onChange:(selectedKeys,selectedRows)=>{props.setMaterialCode(selectedRows)},
      }}
      scroll={{y:350}}
      options={false}
      actionRef={props.table_ref}
      // request={async (param)=>{
      //   const y=await s_getMaterialDocumentCraft({x_id:1,cate_id:[],id:0})
      //   //  alert(JSON.stringify(y.data[0]));
      //    const x=y.data[0].filter((item:any)=>item.code.includes(param.code?param.code:'')
      //                              &&item.name.includes(param.name?param.name:'')
      //                              &&item.invstd.includes(param.invstd?param.invstd:'')
      //                               );
      //     alert(JSON.stringify('666'));                  
      //   return {
      //     data:x,
      //     success:true,
      //   }
      // }}
      
      />
//      存货工艺表
//  useRequest(()=>s_getMaterialDocumentCraft({x_id:1,cate_id:[],id:0}),{
//          onSuccess:(data:any)=>{
//           //  alert(JSON.stringify(data));
//             setTdata(data[0]);
//          },
//      }
//   );
     );

}
 

interface DataType{
  x_id:number,
  id:number, 
  cate_id:number,
  material_id?:number,
  code:string,
  name:string,
  scode:string,
  cate_code:string,
  invstd:string,
  invstd2:string,
  brand:string,
  isservice:number,
  isfee:number,
  munit_code:string,
  aunit_code:string,
  rate:number,
  status:number,
  operate_time:string,
  operater_code:string,
  addition:string,
  fnsku:string,ansi:string,
  //以下4个为视图中添加
  cate_name:string,
  operater_name:string,
  munit_name:string,
  aunit_name:string,
  //默认工艺流程和版本、日期
  craft_route_name?:string,craft_route_version?:string,craft_date?:string,isdefault?:number,
};
 
//工艺流程列表-------------------------------
interface DataTypeRoute{
  id?:number,code?:string,name?:string,version?:string,isdefault?:number,craft_route_id?:number,status?:number,
 };
const columnsRoute:ProColumns<DataTypeRoute>[]=[
  {dataIndex:'id',title:'ID'},{dataIndex:'name',title:'工艺名称'},
  {dataIndex:'version',title:'版本'}
  ,{dataIndex:'isdefault',title:'默认',valueType:'select',
    valueEnum:{0:{text:'否'},1:{text:'是'}}},
    {dataIndex:'status',title:'状态',render:(text:any)=>status2text(text)}
];
//流程明细表/工序------------------------------
interface DataTypeCard{
  // id,mid,code,name,card_id,default_workcenter_id,default_workgroup_id,default_workcenter_name,defalut_workgroup_name
  id?:number,mid?:number,code?:string,name?:string,card_id?:number,default_workcenter_id?:number,
  default_workgroup_id?:number,default_workcenter_name?:string,default_workgroup_name?:string,
  sno?:number,isend?:number,iscommission?:number,
};
const columnsCard:ProColumns<DataTypeCard>[]=[
  // {dataIndex:'id',title:'ID'},
  {dataIndex:'sno',title:'顺序号'},
  {dataIndex:'isend',title:'末工序',render:(text)=>text==1?'是':'否'},
  {dataIndex:'iscommission',title:'委外',render:(text)=>text==1?'是':'否'},
  {dataIndex:'name',title:'工序名'},
  {dataIndex:'default_workcenter_name',title:'默认工作中心'},
  {dataIndex:'default_workgroup_name',title:'默认工作组'},
];
//工序的工作组明细表----------------------------
interface DataTypeItem{
  id?:number,card_id?:number,workgroup_id?:number,workgroup_name?:string,
};
const columnsItem:ProColumns<DataTypeItem>[]=[
  {dataIndex:'id',title:'ID'},{dataIndex:'workgroup_name',title:'工作组名称'},
];
//工作组明细参数表-----------------------------
interface DataTypeParam{
  id?:number,workgroup_id?:number,craft_param_id?:number,code?:string,name?:string,default_value?:string,
};
const columnsParam:ProColumns<DataTypeParam>[]=[
  {dataIndex:'id',title:'ID'},{dataIndex:'name',title:'参数名'},{dataIndex:'default_value',title:'默认值'},
];

///工序用料明细表-----------------------------
interface DataTypeDetail{
  id?:number,pic?:string,quantity_rate?:string,material_id?:number,code?:string,name?:string,invstd?:string,munit_name?:string,quantity?:number
}
const columnsDetail:ProColumns<DataTypeDetail>[]=[
  {dataIndex:'pic',title:'图片' ,editable:false,
    render:(text)=>{
        var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
        return <Image src={pic}  
               style={{width:50,height:50}} alt='无' />
   },
 },
  {dataIndex:'material_id',title:'商品ID'},{dataIndex:'code',title:'SKU编码'},
  {dataIndex:'name',title:'SKU名称'},{dataIndex:'invstd',title:'规格'},
  {dataIndex:'munit_name',title:'计量单位'},{dataIndex:'quantity_rate',title:'换算率'},
  // {dataIndex:'quantity',title:'用量'},
   
];


const Welcome: React.FC = () => {
  //选中的商品分类码。因需用于新增表单中，故{}
  const [selectedCategory,setSelectedCategory]=useState(0);       //选择的分类ID
  const [selectedCateNode,setSelectedNode]=useState<{title:string}>();            //选择的树节点
  const [treeData,setTreeData]=useState();                        //分类树数据源
  const [tdata,setTdata]=useState();                               //档案表格数据源
  const [selectedRecords,setSelectedRecords]=useState<DataType[]>([]);           //选中的商品编码,

  const [open,setOpen]=useState(false);
  const [openRoute,setOpenRoute]=useState(false);//显示工艺流程窗口
  const [openCard,setOpenCard]=useState(false);//显示工序卡片窗口
  const [etypeRoute,setEtypeRoute]=useState(0);   //1新增 0修改
  const [openMaterial,setOpenMaterial]=useState(false);//调出工序用料明细，可按商品BOM版本号及对应明细生成
   
  const [selectedRoute,setSelectedRoute]=useState<DataTypeRoute[]>([]); 
  const [selectedCard,setSelectedCard]=useState<DataTypeCard[]>([]);
  const [selectedItem,setSelectedItem]=useState<DataTypeItem[]>([]);

  const [selectedKeys,setSelectedKeys]=useState<any[]>([]);//树选择的本级节点及下节点
  
  const form_refRoute=useRef<ProFormInstance>();//工艺流程
  const table_refRoute=useRef<ActionType>();//工艺流程
  const form_refCard=useRef<ProFormInstance>();//工序编辑默认表单
  const form_refCardTable=useRef<ProFormInstance>();//工序界面表单，为方便设置table值
  const table_refCard=useRef<ActionType>();//工序细化
  const table_refItem=useRef<ActionType>();//工作组项
  const form_refParam=useRef<ProFormInstance>();//默认参数
  const table_refParam=useRef<ActionType>();//默认参数
  

  const table_refBom=useRef<ActionType>();//BOM子端配置表
  const etable_refBom=useRef<EditableFormInstance>();//BOM子件可编辑表
  const form_refBom=useRef<ProFormInstance>();//BOM子件表单
  const [bomDetail,setBomDetail]=useState<DataTypeBom[]>([]);//表单选择工艺路线后，调出BOM明细
  const [material,setMaterial]=useState([]);//查询商品组件结果
 
  const etable_refbom=useRef<EditableFormInstance>();//BOM明细表
  const [expandKeys,setExpandKeys]=useState([]);
 
 //此处创建一个生成树的通用方法，通过传入表名和X_ID值
 useRequest(()=>getCommTreeByXid({x_id:1,source_table:'material_category'}),{  
  onSuccess:(data)=>{
    setTreeData(data.ctree);
    setExpandKeys(data.keys);
  },
});

  //获取存货工艺表
 useRequest(()=>s_getMaterialDocumentCraft({x_id:1,cate_id:[],id:0}),{
         onSuccess:(data:any)=>{
          //  alert(JSON.stringify(data));
            setTdata(data[0]);
         },
     }
  );

  //当组件选择商品时，更新表格并重载--------------
    useEffect(()=>{
                 if(material.length>0){
                 var x:any[]=etable_refBom.current?.getRowsData?.();
                 // alert(JSON.stringify(x));
                 if(x==undefined)
                    x=[];
                 material.map((item:any)=>{
                    x?.push({rid:Math.random().toFixed(10),id:Math.random().toFixed(10).toString(),
                              material_id:item.id,code:item.code,name:item.name,
                              invstd:item.invstd,invstd2:item.invstd2,munit_name:item.munit_name,  
                              quantity_rate:'1/1', isbelongorder:1,
                              userdefine_id:'[]',pic:item.pic,
                    });
                 });
                 // alert(JSON.stringify(x));
                //  setDataSource(x);
                  
                 form_refBom.current?.setFieldValue('editortable',x);
                 table_refBom.current?.reloadAndRest?.();
              }
              },[material]);
  
 
 // BOM子件用料选择   2025-03-25----------------------------
interface DataTypeBom{
  // rid,mid,id,code,name,invstd,invstd2,pic,rate,munit_name
  rid?:number,mid?:number,id?:number,code?:string,name?:string,invstd?:string,
  invstd2?:string,pic?:string,quantity_rate?:string,munit_name?:string,
}
const columnsBom:ProColumns<DataTypeBom>[]=[
  {dataIndex:'pic',title:'图片' ,editable:false,
      render:(text)=>{
          var pic=text=="-"||text==undefined?"":"/basis_api/file/get?filename="+text;
          return <Image src={pic}  
                 style={{width:50,height:50}} alt='无' />
     },
   },
  {dataIndex:'rid',title:'rid',editable:false,},{dataIndex:'id',title:'id',editable:false,},
  {dataIndex:'code',title:'SKU编码',editable:false,},{dataIndex:'name',title:'名称',editable:false,},
  {dataIndex:'invstd',title:'规格',editable:false,},{dataIndex:'invstd2',title:'型号',editable:false,},
  {dataIndex:'munit_name',title:'计量单位',editable:false,},{dataIndex:'quantity_rate',title:'子件换算率'},
  {
    title:'操作',            
    fixed:'right',
    valueType:'option',
    width:80,
    editable:false,
    render:(text,record,_,action)=>[
      //  <a key='edit2'
      //     onClick={()=>{
      //         alert(record.rid);
      //        action?.startEditable?.(record.rid);}}
      //  >
      //      编辑
      //  </a>,
       <a  key='del2'
           onClick={()=>{
             var x:any[]=etable_refBom.current?.getRowsData?.();
             //  alert(JSON.stringify(x));
               setBomDetail(x.filter((item)=>item.id!=record.id));
             // alert(JSON.stringify(x.filter((item)=>item.id!=record.id)));
             // mtable2_ref.current?.reloadAndRest?.();
             form_refBom.current?.setFieldValue('editortable',x.filter((item)=>item.rid!=record.rid));
           }}
       >
           删除
       </a>,
    ]
 }
   
];

  //根据左侧选择的类别，右侧表格显示明细--注意：此处传入的是树节点node(key,title) 
  //---先取本节点及下级节点值，再共同选---------------------------------------------开始-----------------
  var arr:any[]=[];
   //定义一个递归函数，获取选中节点下的所有key
   function getNodeKeys(node:{key:any,title:any,children:any[]}){
        if(node.children.length>0)
              node.children.map((item:any)=>{
                 arr.push(item.key);
                 if(item.children.length>0){
                      arr.push(getNodeKeys(item));
                 }
             });
      }

  async function getMaterial(node:any){
     // alert( (curCategory));
      setSelectedRecords([]);
      setSelectedCategory(node.key);
      setSelectedNode(node);
     
     arr=[];//先置为空，再取数据
     arr.push(node.key);
     getNodeKeys(node);
     setSelectedKeys(arr.filter((item)=>item!=null));//当前选中的组织的所有下级ID

     const x=await s_getMaterialDocumentCraft({x_id:1,cate_id:arr,id:0});
     //alert(JSON.stringify(x.data[0]));
     setTdata(x.data[0]);
     table_refRoute.current?.reloadAndRest?.();
  }
 //---先取本节点及下级节点值，再共同选---------------------------------------------结束-----------------
  //设置工艺流程按钮
  async function openCraft(){
     if(selectedRecords.length===0)
         message.warning('请先选择要设置的工艺流程。');
      else{
        setOpen(true);
        // const p=await s_getTableInfo({source:'material_param',id:selectedRecords[0].id});
         
      };
  }

  //保存工艺流程
  async function saveCraftRoute(){
     //先取表单的数据，再保存。
     const fdata0=form_refRoute.current?.getFieldsValue();
     const fdata={...fdata0,id:selectedRecords[0]?.id,
                   cate_id:etypeRoute===1?selectedCategory:selectedRecords[0]?.cate_id,
                  };
      //调用远程服务保存//保存基本信息    
     const x=await s_updateInfo({x_id:1,operater_id:1,etypeRoute,fdata});
             
     if(x.success){
        message.success('数据保存成功。');
        setOpenRoute(false);
        setTdata(x.data);
     
        //更新工艺流程表
        table_refRoute.current?.reset?.();
      }
      else
        message.error('数据保存失败，请检查。');
  }

  //工艺线窗口：新增和编辑----------------------------------------
  function addRoute(){
        setEtypeRoute(1);
        setOpenRoute(true);
  };


  function editRoute(){
     if(selectedRoute.length==0)
        message.warning('请先选择要编辑的工艺');
      else{
         setEtypeRoute(0);
         setOpenRoute(open);
       }
};
async function saveRoute(){
   const fdata=form_refRoute.current?.getFieldsValue();
  //  alert(JSON.stringify(fdata));
   const x=await s_updateInfo({x_id:1,operater_id:1,source:'material_craft_route',etype:etypeRoute,fdata});
   if(x.success){
      message.success('保存成功');
      table_refRoute.current?.reloadAndRest?.();
      }
    else
      message.error('保存失败，请联系管理员');
}

// 设置工序卡片默认值  2025-03-24--------------------------------------------------------------------
function setCard(){
    if(selectedCard.length==0)
      message.warning('请选择要设置的卡片');
    else
      setOpenCard(true);
};
async function saveCard(){
    const fdata=form_refCard.current?.getFieldsValue();
    // alert(JSON.stringify(fdata));
     const x=await s_updateInfo({x_id:1,operater_id:1,source:'material_craft_route_card',etype:0,fdata});
   if(x.success){
      message.success('保存成功');
      table_refCard.current?.reloadAndRest?.();
      }
    else
      message.error('保存失败，请联系管理员');
}
   
// BOM子件配置表   2025-03-24----------------------------------------------
async function editBomMaterial(){
  if(selectedCard.length==0)
    message.warning('请选选择工序卡片');
  else{
    //读取工序卡片对应的商品明细，并更新到表格
    // alert(JSON.stringify(selectedCard[0]));
      setOpenMaterial(true);
    // form_refBom.current?.setFieldValue('editortable',x.data);
    
  };
}
// 当选择BOM时，自动调出子件明细
async function getBomDetail(value:number){
  const x=await s_getTableInfo({source:'v_bom_detail',x_id:1, id:value});
  // alert(JSON.stringify(x.data));
  setBomDetail(x.data);
  form_refBom.current?.setFieldValue('editortable',x.data);


};
 // 全部开始编辑，置表格为编辑状态
    function quote(){
                  //用一个循环
                  const x:any[]=etable_refBom.current?.getRowsData?.();
                  if(x!=undefined&&x.length>0)
                    x.map((item:any,index)=>{
                        table_refBom.current?.startEditable?.(index);
                     }
                  );
                  else
                    message.warning('没有任何修改');
                }

async function saveBomMaterial(){
  // 修改保存界面状态
  // alert(JSON.stringify(1));
  const temp=etable_refBom?.current?.getRowsData?.();
  temp?.map((item,index)=>{
      table_refBom.current?.saveEditable?.(index);
  });
  
   var fdata=form_refBom.current?.getFieldsValue();
  //  alert(5);
   fdata={...fdata,
          card_mid:selectedCard&&selectedCard.length>0?selectedCard[0].id:0};
    // alert(JSON.stringify(fdata));
  //  alert(6);
   form_refCardTable.current?.setFieldValue('bomdetail',temp);
  //  alert(JSON.stringify(fdata));
  //更新工序用料表
   const x=await s_updateInfo({x_id:1,source:'material_craft_route_card_bom',operater_id:1,fdata});
  if(x.success){
      message.success('保存成功');
     }
  else 
     message.error('保存失败，请联系管理员。');

}

//退出工艺流程主界面
function exitMain(){
   setSelectedCard([]);
   setSelectedRoute([]);
   setOpen(false);
};
//退出卡片编辑
function exitCard(){
   
  setOpenCard(false);
};
//退出商品编辑
function exitMaterial(){
  setOpenMaterial(false);
};
//退出卡片编辑
function exitRoute(){
  setOpenRoute(false);
};

  // 主界面===========================================================================================
  return<>
     <Row gutter={10}>
     <Col  span={5}>
     <Card title='商品分类' style={{height:'85vh',overflow:'auto'}}>
         {/* <CategoryTree tdata={treeData} getTreeInfo={getMaterial}/> */}
         <Tree treeData={treeData} expandedKeys={expandKeys} 
                  onExpand={(ekeys:any)=>setExpandKeys(ekeys)}
                   onClick={(e,node)=>getMaterial(node)}
           />
     </Card>
     </Col>
     <Col  span={19}>
      <Card title='商品工艺流程档案'  style={{height:'85vh',overflow:'auto'}}  
      extra={<Space size='large'>
                  <Button  onClick={()=>openCraft()}>设置工艺流程</Button>
            </Space>}
      >
     
       <MaterialTable tdata={tdata} setMaterialCode={setSelectedRecords} table_ref={table_refRoute}/>

      </Card>
      </Col>
     </Row>

{/* 工艺流程编辑界面------------------------------------------------------------ */}
<Modal open={open} width='95%' destroyOnClose onCancel={()=>exitMain()} onClose={()=>exitMain()}
     cancelButtonProps={{hidden:true}} okButtonProps={{hidden:true}} style={{top:20}} >
     <ProCard title='商品工艺流程对照' style={{height:900}}
       extra={<Space>
          <Button onClick={()=>addRoute()}>新增工艺流程</Button>
          <Button onClick={()=>editRoute()}>编辑工艺流程</Button>
          <Button onClick={()=>setCard()}>设置工序卡片</Button>
          {/* <Button onClick={()=>message.warning('暂不设置参数')}>设置工序参数</Button> */}
          <Button onClick={()=>editBomMaterial()}>设置工序用料明细</Button>
          {/* <Button>冻结工艺流程</Button>
          <Button>恢复工艺流程</Button> */}
       </Space>} >
         <Row gutter={8}>
            <Col span={12}>
               <Row gutter={2}>
                   <Col span={12}>
                   {/* {JSON.stringify(selectedRecords)} */}
                     <ProCard title='工艺流程' style={{height:'100%',overflow:'auto'}}>
                      <ProTable<DataTypeRoute>
                          actionRef={table_refRoute}
                          search={false}
                          options={false}
                          columns={columnsRoute}
                          rowKey='id'
                          rowSelection={{
                            type:'radio',
                            onChange(selectedRowKeys, selectedRows, info) {
                                setSelectedRoute(selectedRows);
                                table_refCard.current?.reloadAndRest?.();
                            },
                          }}
                          request={async ()=>{
                            // x_id,cate_id,id,source,fdata
                            const x=await s_getcommontableinfo({x_id:1,cate_id:[],
                                           id:selectedRecords.length>0?selectedRecords[0].id:0,
                                           source:'v_material_craft_route'});
                            // alert(JSON.stringify(x.data[0]));
                            return {
                              data:x.data[0],
                              success:true,
                            }
                          }}
                        />
                      </ProCard>
                   </Col>
                   <Col span={12}>
                   <ProCard title='工序卡片' style={{height:'100%',overflow:'auto'}}>
                    {/* {JSON.stringify(selectedRoute)} */}
                   <ProTable<DataTypeCard>
                          search={false}
                          options={false}
                          columns={columnsCard}
                          rowKey='id'
                          actionRef={table_refCard}
                          rowSelection={{
                            type:'radio',
                            async onChange(selectedRowKeys, selectedRows, info) {
                                setSelectedCard(selectedRows);
                                if(selectedRows.length!=0){
                                const card_mid=selectedRows.length>0?selectedRows[0].id:0;
                                // alert(JSON.stringify(selectedRows));
                                // alert(JSON.stringify(card_mid));
                                const x=await s_getTableInfo({x_id:1,source:'v_material_craft_route_card_bom',
                                         id:card_mid});
                                // alert(JSON.stringify(x.data));
                                if(x.data==undefined)
                                    setBomDetail([]);
                                else
                                    setBomDetail(x.data);
                                form_refCardTable.current?.setFieldValue('bomdetail',x.data);
                                };
                            },
                          }}
                          request={async ()=>{
                            // x_id,cate_id,id,source,fdata
                            const x=await s_getcommontableinfo({x_id:1,cate_id:[],
                                           id:selectedRoute.length>0?selectedRoute[0].id:-1,
                                           source:'v_material_craft_route_card2'});
                            //  alert(JSON.stringify(x.data[0]));
                            return {
                              data:x.data[0],
                              success:true,
                            }
                          }}
                        />
                    </ProCard>
                   </Col>
               </Row>
               {/* <Row gutter={2}>
                   <Col span={12}>
                   <ProCard title='工作组' style={{height:400,overflow:'auto'}}>
                   <ProTable<DataTypeItem>
                          search={false}
                          options={false}
                          columns={columnsItem}
                          rowKey='id'
                        />
                    </ProCard>
                   </Col>
                   <Col span={12}>
                   <ProCard title='默认参数' style={{height:400,overflow:'auto'}}>
                   <ProTable<DataTypeParam>
                          search={false}
                          options={false}
                          columns={columnsParam}
                          rowKey='id'
                        />
                    </ProCard>
                   </Col>
               </Row> */}
            </Col>
            <Col span={12}>
            <ProCard title='工序用料明细' style={{height:'100%',overflow:'auto'}}>
            <ProForm formRef={form_refCardTable} submitter={false}>
               <EditableProTable<DataTypeDetail>
                   name='bomdetail'
                   editableFormRef={etable_refbom}
                   search={false}
                   options={false}
                   columns={columnsDetail}
                   rowKey='id'
                   recordCreatorProps={false}
                        />
            </ProForm>
                </ProCard>
            </Col>
         </Row>
       
       </ProCard>
</Modal>

{/* 增加或编辑工艺流程----------------------- */}
<Modal open={openRoute} destroyOnClose onCancel={()=>exitRoute()} onClose={()=>exitRoute()}
   closable okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} width={600}>
    <ProCard title={etypeRoute==1?'新增工艺流程':'编辑工艺流程'} style={{height:390}}
       extra={<Space>
        <Button onClick={()=>form_refRoute.current?.submit()}>保存设置</Button>
        <Button onClick={()=>exitRoute()}>退出</Button>
       </Space>} >
       <ProForm formRef={form_refRoute} layout='horizontal' labelAlign='left' labelCol={{offset:0,span:5}}
            labelWrap  submitter={false}  onFinish={()=>saveRoute()} style={{marginLeft:20}}
            initialValues={etypeRoute==1?{
                 status:1,isdefault:1, material_id:selectedRecords.length>0?selectedRecords[0].id:0,
                 }:{...selectedRoute[0],
                    
                 }}
            >
              <ProFormText name='material_id' hidden={true}/>
              <ProFormText name='id' hidden={true} />
              {/* {JSON.stringify(selectedRoute)} */}
             <ProFormSelect name='craft_route_id' label='工艺流程' width={200}
                 rules={[{required:true,message:'必填项'}]}
                 showSearch
                 request={async ()=>{
                       const x=await s_getSelectData({x_id:1,source:'craft_route'});
                        return x.data;
                     }}
             />
             <ProFormRadio.Group name='isdefault' label='是否默认' 
                 options={[{value:0,label:'否'},{value:1,label:'是'}]} />
             
              <ProFormRadio.Group name='status' label='状态' 
                 rules={[{required:true,message:'必填项'}]}
                 options={[{value:1,label:'正常'},{value:2,label:'冻结'},{value:3,label:'删除'}]} />
        </ProForm>
       </ProCard>

 </Modal>
     {/* 设置工序卡片----------------------------------- */}
     <Modal open={openCard} destroyOnClose closable onCancel={()=>exitCard()}
            onClose={()=>exitCard()}
          okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}} width={600}  style={{top:20}}>
         <ProCard title='设置工序卡片默认值'  style={{height:600}}
            extra={<Space>
              <Button onClick={()=>form_refCard.current?.submit()}>保存</Button>
              <Button onClick={()=>exitCard()}>退出</Button>
            </Space>}  >
              <ProForm formRef={form_refCard} submitter={false} layout='horizontal' labelAlign='left' 
                  labelCol={{offset:0,span:5}}
                  initialValues={selectedCard.length>0?{...selectedCard[0]}:{isend:0,iscommission:0}}
                  onFinish={()=>saveCard()}
                  >
                    {/* {JSON.stringify(selectedCard)} */}
                   <ProFormText name='craft_route_mid' hidden={true} />
                   <ProFormText name='sno' label='顺序号' width={200}
                      rules={[{required:true,message:'必填项'}]}
                   />
                   <ProFormSelect name='card_id' label='工序'  width={200}
                   rules={[{required:true,message:'必填项'}]}
                        showSearch
                        request={async ()=>{
                           const x=await s_getSelectData({x_id:1,source:'craft_card'});
                           return x.data;
                         }}
                   />
                   <ProFormSelect name='default_workcenter_id' label='默认工作中心'  width={200}
                    
                        showSearch
                        request={async ()=>{
                           const x=await s_getSelectData({x_id:1,source:'workcenter'});
                           return x.data;
                         }}
                   />
                  <ProFormSelect name='default_workgroup_id' label='默认工作组' width={200} 
                      showSearch
                      request={async ()=>{
                        const x=await s_getSelectData({x_id:1,source:'workgroup'});
                         return x.data;
                       }}   
                   />

                   <ProFormRadio.Group name='iscommission' label='是否委外' width={200} 
                       rules={[{required:true,message:'必填项'}]}
                       options={[{value:1,label:'是'},{value:0,label:'否'}]} 
                   />
                  
                  <ProFormRadio.Group name='isend' label='是否末工序' 
                     rules={[{required:true,message:'必填项'}]}
                     options={[{value:1,label:'是'},{value:0,label:'否'}]} />
                  </ProForm>
          </ProCard>
  
      </Modal>

      {/* 给工序卡片，配置子件的用料明细。来自于商品的BOM   2025-03-24------------------------ */}
      <Modal open={openMaterial} destroyOnClose closable onCancel={()=>exitMaterial()} 
        onClose={()=>exitMaterial()} okButtonProps={{hidden:true}} cancelButtonProps={{hidden:true}}
        style={{top:10}} width='80%'>
         <ProCard title='编辑工序子件用料表'  style={{height:700}}
            extra={<Space>
              <QueryMaterial2 setData={setMaterial} type='checkbox' x_id={1}/>
              <Button onClick={()=>quote()}>编辑用量</Button>
              <Button onClick={()=>form_refBom.current?.submit()}>保存</Button>
              <Button onClick={()=>exitMaterial()}>退出</Button>
            </Space>}>
            {/* {JSON.stringify(bomDetail)} */}
             <ProForm formRef={form_refBom} submitter={false} layout='horizontal' labelAlign='left'
                labelCol={{offset:0,span:2}}
                initialValues={
                     bomDetail.length>0?{editortable:bomDetail,card_id:selectedCard.length>0?selectedCard[0].card_id:0}:
                             {card_id:selectedCard.length>0?selectedCard[0].card_id:0}}
                onFinish={()=>saveBomMaterial()}
                >
                  {/* {JSON.stringify(selectedCard[0])} */}
                <ProFormText name='card_id' label='工序ID' hidden />
                <ProFormSelect name='bom_id' label='指定BOM版本' width={200}
                    showSearch
                    request={async ()=>{
                      const x=await s_getSelectDataByCondition({x_id:1,source:'bomVersion',
                                      fdata:{material_id:selectedRecords.length>0?selectedRecords[0].id:0}});
                         return x.data;
                     }}
                     onChange={async (value:any,option)=>{
                         getBomDetail(value);  
                     }}
                />
                <EditableProTable<DataTypeBom> 
                   name='editortable'
                   rowKey='rid'
                   dataSource={bomDetail}
                   columns={columnsBom}
                   editableFormRef={etable_refBom}
                   actionRef={table_refBom}
                  //  rowSelection={{
                  //    type:'radio',
                  //  }}
                   recordCreatorProps={false}
                   search={false}
                   options={false}
                   editable={{
                    type:'multiple',
                   }}
                />

                </ProForm>
            </ProCard>
      </Modal>
  </>
};

export default Welcome;


